<template>
  <view class="container">
    <!-- 头部 -->
    <view class="header">
      <text class="title">编辑Banner</text>
    </view>

    <!-- 表单内容 -->
    <view class="form">
      <view class="form-item">
        <text class="label">Banner名称</text>
        <input 
          v-model="formData.title" 
          class="input" 
          placeholder="请输入Banner名称"
          maxlength="50"
        />
        <text class="char-count">{{ formData.title?.length || 0 }}/50</text>
      </view>



      <view class="form-item">
        <text class="label">Banner图片URL</text>
        <view class="url-input-group">
          <input 
            v-model="imageUrl" 
            class="input" 
            placeholder="请输入图片URL地址"
          />
          <button class="add-image-btn" @click="addImage">添加图片</button>
        </view>
        <text class="hint">建议使用网络图片URL，如：https://example.com/image.jpg</text>
        <view v-if="imageUrl && imageUrl.trim() !== ''" class="image-preview">
          <image 
            :src="imageUrl" 
            class="preview-image"
            mode="aspectFill"
            @error="handleImageError"
          />
          <text class="preview-url">{{ imageUrl }}</text>
        </view>
      </view>

      <view class="form-item">
        <text class="label">跳转链接类型</text>
        <radio-group class="radio-group" @change="handleLinkTypeChange">
          <label class="radio-item">
            <radio value="0" :checked="formData.link_type === '0'" />
            <text class="radio-text">无跳转</text>
          </label>
          <label class="radio-item">
            <radio value="1" :checked="formData.link_type === '1'" />
            <text class="radio-text">外部链接</text>
          </label>
          <label class="radio-item">
            <radio value="2" :checked="formData.link_type === '2'" />
            <text class="radio-text">应用内页面</text>
          </label>
        </radio-group>
        <text class="hint">选择Banner点击后的跳转行为</text>
      </view>

      <view class="form-item">
        <text class="label">跳转链接</text>
        <input 
          v-model="formData.link_value" 
          class="input" 
          :disabled="formData.link_type === '0'"
          :placeholder="getLinkPlaceholder()"
        />
        <text class="hint">
          {{ getLinkHint() }}
        </text>
      </view>

      <view class="form-row">
        <view class="form-item half">
          <text class="label">排序</text>
          <input 
            v-model="formData.sort" 
            class="input" 
            type="number"
            placeholder="0"
          />
          <text class="hint">数字越小越靠前</text>
        </view>

        <view class="form-item half">
          <text class="label">状态</text>
          <radio-group class="radio-group" @change="handleStatusChange">
            <label class="radio-item">
              <radio value="1" :checked="formData.status === '1'" />
              <text class="radio-text">启用</text>
            </label>
            <label class="radio-item">
              <radio value="0" :checked="formData.status === '0'" />
              <text class="radio-text">禁用</text>
            </label>
          </radio-group>
        </view>
      </view>



    </view>

    <!-- 操作按钮 -->
    <view class="actions">
      <button class="btn cancel" @click="handleCancel">取消</button>
      <button class="btn submit" @click="handleSubmit">保存</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 响应式数据
const formData = reactive({
  _id: '',
  title: '',
  image: '',
  link_type: 0, // 0:无跳转, 1:外部链接, 2:应用内页面
  link_value: '',
  sort: 0,
  status: 1,
  create_date: '',
  update_date: ''
})

const loading = ref(false)
const imageUrl = ref('')

// 页面加载
onLoad((options) => {
  if (!options.id) {
    uni.showToast({
      title: 'Banner ID不存在',
      icon: 'error'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
    return
  }
  
  formData._id = options.id

  loadBannerDetail()
})

// 加载Banner详情
const loadBannerDetail = async () => {
  loading.value = true
  try {
    const result = await uniCloud.callFunction({
      name: 'food-banners',
      data: {
        action: 'get-banner-detail',
        data: {
          bannerId: formData._id
        }
      }
    })

    if (result.result.code === 200) {
      Object.assign(formData, result.result.data)
      
      // 确保link_type是字符串类型，因为radio的value是字符串
      if (formData.link_type !== undefined) {
        formData.link_type = String(formData.link_type)
      }
      
      // 确保status是字符串类型
      if (formData.status !== undefined) {
        formData.status = String(formData.status)
      }
      
      // 正确处理banners的image字段（文件对象类型）
      if (formData.image && typeof formData.image === 'object' && formData.image.url) {
        // 如果是文件对象且有url属性，使用url作为图片地址
        imageUrl.value = formData.image.url
      } else if (typeof formData.image === 'string') {
        // 如果是字符串类型，直接使用
        imageUrl.value = formData.image
      } else {
        // 其他情况设为空
        imageUrl.value = ''
      }
    } else {
      uni.showToast({
        title: result.result.message || '获取Banner详情失败',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  } catch (error) {
    console.error('获取Banner详情失败:', error)
    uni.showToast({
      title: '获取Banner详情失败',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } finally {
    loading.value = false
  }
}

// 添加图片
const addImage = () => {
  if (!imageUrl.value || imageUrl.value.trim() === '') {
    uni.showToast({
      title: '请输入图片URL地址',
      icon: 'none'
    })
    return
  }
  
  // 简单的URL格式验证
  if (!imageUrl.value.startsWith('http://') && !imageUrl.value.startsWith('https://')) {
    uni.showToast({
      title: '请输入有效的URL地址（以http://或https://开头）',
      icon: 'none'
    })
    return
  }
  
  formData.image = imageUrl.value.trim()
  uni.showToast({
    title: '图片URL已添加',
    icon: 'success'
  })
}

// 图片加载错误处理
const handleImageError = () => {
  uni.showToast({
    title: '图片加载失败，请检查URL是否正确或是否存在防盗链',
    icon: 'none'
  })
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '--'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

// 表单验证
const validateForm = () => {
  if (!formData.title || formData.title.trim() === '') {
    uni.showToast({
      title: '请输入Banner名称',
      icon: 'none'
    })
    return false
  }
  
  if (formData.title.trim().length > 50) {
    uni.showToast({
      title: 'Banner名称不能超过50个字符',
      icon: 'none'
    })
    return false
  }
  
  
  
  if (!imageUrl.value || imageUrl.value.trim() === '') {
    uni.showToast({
      title: '请添加Banner图片',
      icon: 'none'
    })
    return false
  }
  
  // 根据链接类型进行验证
  if (formData.link_type === '1' && formData.link_value) {
    // 外部链接验证
    if (!formData.link_value.startsWith('http://') && !formData.link_value.startsWith('https://')) {
      uni.showToast({
        title: '外部链接必须以http://或https://开头',
        icon: 'none'
      })
      return false
    }
  } else if (formData.link_type === '2' && formData.link_value) {
    // 应用内页面验证
    if (!formData.link_value.startsWith('/')) {
      uni.showToast({
        title: '应用内页面路径必须以/开头',
        icon: 'none'
      })
      return false
    }
  }
  
  // 如果选择了链接类型但没有填写链接
  if ((formData.link_type === '1' || formData.link_type === '2') && (!formData.link_value || formData.link_value.trim() === '')) {
    uni.showToast({
      title: formData.link_type === '1' ? '请填写外部链接地址' : '请填写应用内页面路径',
      icon: 'none'
    })
    return false
  }
  
  if (formData.sort < 0) {
    uni.showToast({
      title: '排序值不能为负数',
      icon: 'none'
    })
    return false
  }
  
  return true
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) return
  
  loading.value = true
  
  try {
    // 准备云函数期望的数据格式
    const bannerData = {
      title: formData.title, // 映射title字段
      image: formData.image, // 保持原image字段
      link_type: formData.link_type || 0, // 使用用户选择的链接类型
      link_value: formData.link_value || '', // 链接值
      sort: parseInt(formData.sort) || 0,
      status: parseInt(formData.status) || 1
    }
    
    // 编辑模式 - 调用更新接口
    const result = await uniCloud.callFunction({
      name: 'food-banners',
      data: {
        action: 'update-banner',
        data: {
          bannerId: formData._id,
          bannerData: bannerData // 使用正确的字段名
        }
      }
    })
    
    if (result.result.code === 200) {
      uni.showToast({
        title: '更新成功',
        icon: 'success'
      })
      
      // 延迟跳转到list页面，让用户看到成功提示
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/banners/list'
        })
      }, 500)
    } else {
      uni.showToast({
        title: result.result.message || '更新失败',
        icon: 'error'
      })
    }
  } catch (error) {
    console.error('提交失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

// 获取链接占位符文本
const getLinkPlaceholder = () => {
  switch (formData.link_type) {
    case 0:
      return '选择无跳转时，此输入框被禁用'
    case 1:
      return '请输入外部链接地址（如：https://example.com）'
    case 2:
      return '请输入应用内页面路径（如：/pages/index/index）'
    default:
      return '请输入跳转链接'
  }
}

// 处理链接类型变化
const handleLinkTypeChange = (event) => {
  const newLinkType = event.detail.value
  formData.link_type = newLinkType
  
  // 如果选择无连接，自动清空链接输入框
  if (newLinkType === '0') {
    formData.link_value = ''
  }
}

// 处理状态变化
const handleStatusChange = (event) => {
  formData.status = event.detail.value
}

// 获取链接提示文本
const getLinkHint = () => {
  switch (formData.link_type) {
    case 0:
      return '选择无跳转时，Banner点击后不会跳转'
    case 1:
      return '用户点击Banner后跳转的外部链接地址'
    case 2:
      return '用户点击Banner后跳转的应用内页面路径'
    default:
      return '用户点击Banner后跳转的链接地址'
  }
}

// 取消操作
const handleCancel = () => {
  uni.showModal({
    title: '提示',
    content: '确定要取消编辑吗？所有未保存的更改将丢失。',
    success: (res) => {
      if (res.confirm) {
        uni.navigateBack()
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 32rpx;
}

.header {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

.form {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.form-item {
  margin-bottom: 48rpx;
  position: relative;
  
  .label {
    display: block;
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 16rpx;
  }
  
  .input {
    width: 100%;
    height: 80rpx;
    border: 2rpx solid #e9ecef;
    border-radius: 12rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    background: #ffffff;
    
    &:focus {
      border-color: #007aff;
      outline: none;
    }
    
    &::placeholder {
      color: #999;
    }
  }
  
  .textarea {
    width: 100%;
    min-height: 160rpx;
    border: 2rpx solid #e9ecef;
    border-radius: 12rpx;
    padding: 24rpx;
    font-size: 28rpx;
    background: #ffffff;
    resize: none;
    
    &:focus {
      border-color: #007aff;
      outline: none;
    }
    
    &::placeholder {
      color: #999;
    }
  }
  
  .char-count {
    position: absolute;
    right: 0;
    bottom: -32rpx;
    font-size: 24rpx;
    color: #999;
  }
  
  .hint {
    font-size: 24rpx;
    color: #999;
    margin-top: 8rpx;
  }
}

.form-row {
  display: flex;
  gap: 32rpx;
  
  .form-item.half {
    flex: 1;
  }
}

.url-input-group {
  display: flex;
  gap: 16rpx;
  align-items: center;
  
  .input {
    flex: 1;
  }
  
  .add-image-btn {
    width: 160rpx;
    height: 80rpx;
    background: #007aff;
    color: #ffffff;
    border: none;
    border-radius: 8rpx;
    font-size: 26rpx;
    white-space: nowrap;
    
    &:active {
      background: #0056cc;
    }
  }
}

.image-preview {
  margin-top: 24rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  
  .preview-image {
    width: 200rpx;
    height: 200rpx;
    border-radius: 12rpx;
    border: 2rpx solid #e9ecef;
  }
  
  .preview-url {
    font-size: 24rpx;
    color: #666;
    word-break: break-all;
    background: #f8f9fa;
    padding: 16rpx;
    border-radius: 8rpx;
    border: 1rpx solid #e9ecef;
  }
}

.radio-group {
  display: flex;
  gap: 48rpx;
  
  .radio-item {
    display: flex;
    align-items: center;
    gap: 12rpx;
    
    .radio-text {
      font-size: 26rpx;
      color: #333;
    }
  }
}

.readonly-field {
  .readonly-text {
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}

.actions {
  display: flex;
  gap: 32rpx;
  margin-top: 64rpx;
  
  .btn {
    flex: 1;
    height: 88rpx;
    border: none;
    border-radius: 12rpx;
    font-size: 32rpx;
    font-weight: bold;
    
    &.cancel {
      background: #f8f9fa;
      color: #666;
      border: 2rpx solid #e9ecef;
      
      &:active {
        background: #e9ecef;
      }
    }
    
    &.submit {
      background: #007aff;
      color: #ffffff;
      
      &:active {
        background: #0056cc;
      }
    }
  }
}

/* 响应式适配 */
@media (max-width: 750rpx) {
  .container {
    padding: 24rpx;
  }
  
  .form-row {
    flex-direction: column;
    gap: 0;
  }
  
  .form-item.half {
    margin-bottom: 32rpx;
  }
}
</style>